const Router = require('koa-router')
const mongoose = require('mongoose')
const fs = require('fs')

let router = new Router()

router.get('/insertAllGoods', async(ctx) => {
    fs.readFile('./json/newGoods.json', 'utf8', (err, data) => {
        let count = 0
        data = JSON.parse(data)
        const Goods = mongoose.model('Goods')
        data.map((value, index) => {
            let newGoods = new Goods(value)
            newGoods.save().then(() => {
                count ++
                console.log(`保存成功${count}`)
            }).catch((err) => {
                console.log('保存失败')
            })
        })
    })
    ctx.body = '开始导入'
})

router.get('/insertAllCategory', async(ctx) => {
    fs.readFile('./json/category.json', 'utf8', (err, data) => {
        data = JSON.parse(data)
        const cateGory = mongoose.model('Category')
        let count = 0
        data.RECORDS.map((value, index) => {
            let newCategory = new cateGory(value)
            newCategory.save().then(() => {
                count++
                console.log(`保存成功${count}`)
            }).catch(err => {
                console.log(`保存失败%${err}`)
            })
        })
    })
    ctx.body = '开始导入'
})

router.get('/insertAllCategorySub', async(ctx) => {
    fs.readFile('./json/category_sub.json', 'utf8', (err, data) => {
        data = JSON.parse(data)
        let count = 0
        const Categortysub = mongoose.model('Categortysub')
        data.RECORDS.map((value, index) => {
            let newCategorysub = new Categortysub(value)
            newCategorysub.save().then(() => {
                count++
                console.log(`保存成功${count}`)
            }).catch(err => {
                console.log(`保存失败${err}`)
            })
        })
    })
    ctx.body = '开始导入'
})

router.post('/checkGoodSDetail', async(ctx) => {
    let data = ctx.request.body
    const Goods = mongoose.model('Goods')
    await Goods.findOne({ID: data.goodsId}).exec().then(async (response) => {
        console.log(response)
        ctx.body = {
            code: 200,
            message: response
        }
    }).catch (err => {
        ctx.body = {
            code: 500,
            message: err
        }
    })
})

module.exports = router